package com.cade.agriculturemall.view.personalCenter.personalInfo;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.cade.agriculturemall.base.BasePresenter;
import com.cade.agriculturemall.model.UserInfoEntity;
import com.cade.agriculturemall.widget.MD5Util;
import com.google.gson.Gson;

/**
 * Created by Lobby on 2017/11/29.
 */

public class PersonalInfoPresenter extends BasePresenter<PersonalInfoContract.IView> implements PersonalInfoContract.IPresenter {
    public PersonalInfoPresenter(PersonalInfoContract.IView view) {
        super(view);
    }

    private String mOldMd5;

    @Override
    public void onResume() {

    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onDestroy() {

    }

    @Override
    public void upLoadInfo(UserInfoEntity entity) {
        mView.showProgress();
        AVUser.alwaysUseSubUserClass(UserInfoEntity.class);
        final UserInfoEntity user = AVUser.getCurrentUser(UserInfoEntity.class);
        user.put("logo_url", entity.getLogo_url());
        user.put("nickname", entity.getNickname());
        user.put("sex", entity.getSex());
        user.put("logo_url", entity.getLogo_url());
        user.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if (e != null) {
                    e.printStackTrace();
                    mView.showError(e.getMessage());
                } else {
                    mView.showMessage("修改成功");
                    coverJson(user);
                }
                mView.dismissProgress();
            }
        });
    }

    public String coverJson(UserInfoEntity user) {
        String json = new Gson().toJson(user);
        mOldMd5 = MD5Util.md5Str(json);
        return mOldMd5;
    }

    @Override
    public void downLoadInfo() {
        AVUser.alwaysUseSubUserClass(UserInfoEntity.class);
        UserInfoEntity user = AVUser.getCurrentUser(UserInfoEntity.class);
        mView.getInfo(user);
//            将第一次拉取的数据 转为String json
        coverJson(user);
    }


    //          选择后退，返回上个页面时，收集信息。判断是否做修改，
//          是？弹出提示框：后退
    @Override
    public boolean isHasChange(UserInfoEntity model) {
        String json = new Gson().toJson(model);
        String md5 = MD5Util.md5Str(json);
        if (!md5.equals(mOldMd5)) {
            return true;
        } else {
            return false;
        }
    }
}
